<?php

/**
 * User:ayou chow
 * Date: 2019-12-11
 * Time: 15:11
 */

namespace app\admin\controller;


use app\common\model\GuildManagerModel;
use app\common\model\GuildModel;
use app\common\model\GuildTransferModel;
use app\common\model\GuildUserApplyModel;
use app\common\model\GuildWithdrawalsModel;
use app\common\model\NoticeModel;
use app\common\model\RegSourceModel;
use app\common\model\UserModel;
use think\Db;
use think\facade\Request;
use think\Validate;

class GuildController extends BaseController
{
    public function index()
    {
        return $this->fetch();
    }

    public function add()
    {
        $where       = [
            ['guild_id', '=', 0],
            ['status', '=', 1]
        ];
        $source_list = RegSourceModel::where($where)->field('id,source_key,source_name')->select();
        $this->assign('source_list', $source_list);
        return $this->fetch();
    }

    public function edit()
    {
        $guild = GuildModel::with(['manager' => function ($query) {
            $query->where('role_id', 1);
        }])->where(['id' => Request::param('id')])->find();
        if (empty($guild)) {
            $this->error('未查询到相关数据');
        }

        $where       = "(guild_id=0 OR guild_id = {$guild->id}) and status=1";
        $source_list = RegSourceModel::where($where)->field('id,source_key,source_name,guild_id')->select();

        $this->assign('source_list', $source_list);
        $this->assign('guild', $guild);
        $this->assign('role_id', $this->userinfo->roleid);
        return $this->fetch();
    }

    public function signForCos()
    {
        return parent::signForCos();
    }

    public function getlist()
    {
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [];
        if ($id = Request::param('id')) {
            $where[] = ['id', '=', $id];
        }
        if ($mobile = Request::param('mobile')) {
            // 查询管理员账号
            $guild_idarr = GuildManagerModel::whereLike('mobile', "%{$mobile}%")->where('role_id', 1)->column('guild_id');
            $where[]     = ['id', 'in', $guild_idarr];
        }
        if ($name = Request::param('name')) {
            $where[] = ['name', 'like', "%{$name}%"];
        }
        if ($source = Request::param('source')) {
            // 查询渠道关联的工会id
            $guild_idarr = RegSourceModel::whereLike('source_name', "%{$source}%")->whereOr('id', $source)->column('guild_id');
            $where[]     = ['id', 'in', $guild_idarr];
        }

        $list = GuildModel::with(['admin', 'manager' => function ($query) {
            $query->where('role_id', 1);
        }])->where($where)
            // ->field('download_ratio', true)
            ->limit(($page - 1) * $limit, $limit)
            ->order("create_time", "desc")
            ->select();

        if (count($list) > 0) {
            $list_arr  = $list->toArray();
            $guild_ids = array_column($list_arr, 'id');
            $guild_ids = array_filter(array_unique($guild_ids));

            $member_count = UserModel::field('count(id) as count,guild_id')->whereIn("guild_id", $guild_ids)->group('guild_id')->select()->toArray();
            $member_count = array_column($member_count, 'count', 'guild_id');

            $reg_source = RegSourceModel::field('id,guild_id,source_name')->whereIn('guild_id', $guild_ids)->select();

            foreach ($list as &$guild) {
                $guild->member_count = isset($member_count[$guild->id]) ? $member_count[$guild->id] : 0;
                $reg_source_arr      = array();
                foreach ($reg_source as $val) {
                    if ($guild->id == $val->guild_id) {
                        array_push($reg_source_arr, $val->id . '-' . $val->source_name);
                    }
                }
                $guild->reg_source_str = implode('，', $reg_source_arr);
                if ($guild->manager) {
                    $guild->manager->mobile = mobileHide($guild->manager->mobile, $this->userinfo->roleid);
                }
            }

            $count = GuildModel::where($where)->count();
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function add_post()
    {
        $all_param = Request::param();
        $password  = Request::param('password');
        // 关联渠道id
        $source_ids = Request::param('source_ids');
        $source_ids = array_unique(array_filter(explode(',', $source_ids)));

        $validate = new Validate([
            'mobile'         => 'require|pass:' . config('other.mobile_preg'),
            'password'       => 'require|length:6,12|pass:/^[\S]{6,12}$/',
            'real_name'      => 'require|length:2,16|chsDash',
            'name'           => 'require|length:2,16|chsDash',
            'sharing_ratio'  => 'require|integer|pass:/^[0-9][0-9]*$/|between:0,100',
            'download_ratio' => 'require|integer|pass:/^[0-9][0-9]*$/|between:0,100',
        ], [
            "mobile"            => "请输入正确的手机号",
            "password.require"  => "请输入密码",
            "password.length"   => "密码必须在6-12位之间",
            "password.pass"     => "密码在6-12位且不能有空格",
            "real_name.require" => "真实姓名不能为空",
            "real_name.length"  => "真实姓名在2-16个字符",
            "real_name.chsDash" => "真实姓名中文、英文、_和-组成",
            "name.require"      => "公会名称不能为空",
            "name.length"       => "公会名称在2-16个字符",
            "name.chsDash"      => "公会名称中文、英文、_和-组成",
            "sharing_ratio"     => "公会分成比例在0-100之间",
            "download_ratio"    => "下载量折扣比例在0-100之间",
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        $guild              = new GuildModel($all_param);
        $guild->create_time = date("Y-m-d H:i:s");
        $guild->admin_id    = $this->admin_id;
        //检测手机号是否占用
        $check = GuildManagerModel::get(["mobile" => $guild->mobile]);
        if ($check) {
            return self::bulidFail("手机号已被占用");
        }

        // 公会名称不能重复
        $check_guild_name = GuildModel::where(['name' => $all_param['name']])->find();
        if (!empty($check_guild_name)) {
            return self::bulidFail('公会名称已经存在');
        }


        $guild_manager = new GuildManagerModel($all_param);

        $guild_manager->password      = openssl_encrypt(substr($guild_manager->mobile, strlen($guild_manager->mobile) - 4, 4) . $password, "DES-ECB", $this->OPENSSL_KEY);
        $guild_manager->role_id       = 1;
        $guild_manager->create_time   = date("Y-m-d H:i:s");
        $guild_manager->path_ids      = '0';
        $guild_manager->sharing_ratio = 0;

        Db::startTrans();
        try {
            if (!$guild->save()) {
                throw new \Exception('添加失败');
            }

            $guild_manager->guild_id = $guild->id;
            if (!$guild_manager->save()) {
                throw new \Exception('添加失败');
            }

            // 修改渠道关联公会id
            if ($source_ids) {
                $r_where = [
                    ['id', 'in', $source_ids],
                    ['guild_id', '=', 0],
                ];
                $res     = RegSourceModel::where($r_where)->update(['guild_id' => $guild->id, 'update_time' => date('Y-m-d H:i:s')]);
                if (!$res) {
                    throw new \Exception('使用渠道设置失败');
                }
            }

            // 记录日志
            $log_content = "创建工会信息，ID：{$guild->id}，工会名称：{$guild->name}，手机号：{$guild_manager->mobile}";
            parent::addAdminLog($log_content);

            Db::commit();
            return self::bulidSuccess();
        } catch (\Exception $e) {
            Db::rollback();
        }
        return self::bulidFail();
    }

    public function edit_post()
    {
        $id        = Request::param('id');
        $all_param = Request::param();
        $password  = Request::param('password');
        $mobile    = Request::param('mobile');
        // 关联渠道id
        $source_ids = Request::param('source_ids');
        $source_ids = array_unique(array_filter(explode(',', $source_ids)));
        if (empty($id)) {
            return self::bulidFail();
        }

        $validate = new Validate([
            'mobile'         => 'require|pass:' . config('other.mobile_preg'),
            'real_name'      => 'require|length:2,16|chsDash',
            'name'           => 'require|length:2,16|chsDash',
            'sharing_ratio'  => 'require|integer|pass:/^[0-9][0-9]*$/|between:0,100',
            'download_ratio' => 'require|integer|pass:/^[0-9][0-9]*$/|between:0,100',
        ], [
            "mobile"            => "请输入正确的手机号",
            "real_name.require" => "真实姓名不能为空",
            "real_name.length"  => "真实姓名在2-16个字符",
            "real_name.chsDash" => "真实姓名中文、英文、_和-组成",
            "name.require"      => "公会名称不能为空",
            "name.length"       => "公会名称在2-16个字符",
            "name.chsDash"      => "公会名称中文、英文、_和-组成",
            "sharing_ratio"     => "公会分成比例在0-100之间",
            "download_ratio"    => "下载量折扣比例在0-100之间",
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        $guild = GuildModel::where(['id' => $id])->find();
        if (empty($guild)) {
            return self::bulidFail('公会信息不存在');
        }

        // 公会名称不能重复
        $cg_where = [
            ['name', '=', $all_param['name']],
            ['id', '<>', $guild->id]
        ];

        $check_guild_name = GuildModel::where($cg_where)->find();
        if (!empty($check_guild_name)) {
            return self::bulidFail('公会名称已经存在');
        }

        $guild_manager = GuildManagerModel::where('guild_id', $id)->where('role_id', 1)->find();
        //检测手机号是否占用
        $c_where = [
            ['mobile', '=', $mobile],
        ];
        if (empty($guild_manager)) {
            $guild_manager = new GuildManagerModel();
        } else {
            $c_where[] = ['id', '<>', $guild_manager->id];
        }

        //检测手机号是否占用
        $check_model = GuildManagerModel::where($c_where)->find();
        if (!empty($check_model)) {
            return self::bulidFail("手机号已被占用");
        }

        $guild_manager->guild_id      = $id;
        $guild_manager->role_id       = 1;
        $guild_manager->mobile        = $mobile;
        $guild_manager->path_ids      = '0';
        $guild_manager->real_name     = $all_param['real_name'];
        $guild_manager->sharing_ratio = 0;
        if ($password) {
            if (!preg_match('/^[\S]{6,12}$/', $password)) {
                return self::bulidFail("密码在6-12位且不能有空格");
            }

            $guild_manager->password = openssl_encrypt(substr($mobile, strlen($mobile) - 4, 4) . $password, "DES-ECB", $this->OPENSSL_KEY);
        }

        $guild->admin_id       = $this->admin_id;
        $guild->name           = $all_param['name'];
        $guild->icon           = Request::param("icon");
        $guild->content        = Request::param("content");
        $guild->sharing_ratio  = $all_param['sharing_ratio'];
        $guild->download_ratio = $all_param['download_ratio'];
        $guild->download_reserved = $all_param['download_reserved'];


        Db::startTrans();
        try {
            if (!$guild->save()) {
                throw new \Exception('修改失败');
            }

            if (!$guild_manager->save()) {
                throw new \Exception('修改失败');
            }

            //查询之前是否有设置，如果设置了先重置一下公会id为0
            if (RegSourceModel::where('guild_id', $guild->id)->find()) {
                $res = RegSourceModel::where('guild_id', $guild->id)->update(['guild_id' => 0, 'update_time' => date('Y-m-d H:i:s')]);
                if (!$res) {
                    throw new \Exception('使用渠道设置失败');
                }
            }

            // 修改渠道关联公会id
            if ($source_ids) {
                $r_where = [
                    ['id', 'in', $source_ids],
                    ['guild_id', '=', 0],
                ];
                $res     = RegSourceModel::where($r_where)->update(['guild_id' => $guild->id, 'update_time' => date('Y-m-d H:i:s')]);
                if (!$res) {
                    throw new \Exception('使用渠道设置失败');
                }
            }

            // 记录日志
            $log_content = "修改工会信息，ID：{$guild->id}，工会名称：{$guild->name}，手机号：{$guild_manager->mobile}";
            parent::addAdminLog($log_content);

            Db::commit();
            return self::bulidSuccess();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();
        }
        return self::bulidFail();
    }

    /**
     * 工会成员
     * @return mixed
     */
    public function manager()
    {
        $guild_id = Request::param("guild_id");
        $this->assign('guild_id', $guild_id);
        return $this->fetch();
    }

    public function get_manager_list()
    {
        $page      = Request::param("page");
        $limit     = Request::param("limit");
        $guild_id  = Request::param('guild_id');
        $mobile    = Request::param('mobile');
        $real_name = Request::param('real_name');

        $where = [];
        if ($guild_id) {
            $where[] = ['guild_id', '=', $guild_id];
        }
        if ($mobile) {
            // 查询管理员账号
            $where[] = ['mobile', 'like', "%{$mobile}%"];
        }
        if ($real_name) {
            $where[] = ['real_name', 'like', "%{$real_name}%"];
        }

        // 角色id
        $admin_roleid = $this->userinfo->roleid;

        $list = GuildManagerModel::with(['role', 'parent'])->where($where)
            ->limit(($page - 1) * $limit, $limit)
            ->order("create_time", "desc")
            ->select()
            ->each(function ($query) use ($admin_roleid) {
                $query->mobile = mobileHide($query->mobile, $admin_roleid);
            });

        if (count($list) > 0) {
            $count = GuildManagerModel::where($where)->count();
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function ban_post()
    {
        $id    = Request::param('id');
        $guild = GuildModel::get($id);
        if (!$guild) {
            return self::bulidFail("工会信息不存在");
        }
        $guild->status = Request::param('status');
        if ($guild->save()) {
            // 记录日志
            $log_content = ($guild->status == 1 ? '解封' : '封禁') . "工会，ID：{$guild->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function withdrawals()
    {
        return $this->fetch();
    }

    public function withdraw_edit()
    {
        $id              = Request::param('id');
        $withdrawalsinfo = GuildWithdrawalsModel::get($id);
        $this->assign("withdrawalsinfo", $withdrawalsinfo);
        return $this->fetch();
    }

    public function getWithdrawList()
    {
        $id       = Request::param('id');
        $guild_id = Request::param('guild_id');
        $trade_no = Request::param('trade_no');
        $status   = Request::param('status');

        $where = [];
        if ($id) {
            $where['id'] = $id;
        }
        if ($guild_id) {
            $where['guild'] = $guild_id;
        }
        if ($trade_no) {
            $where['trade_no'] = $trade_no;
        }
        if ($status != null) {
            $where['status'] = $status;
        }

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $orders = GuildWithdrawalsModel::where($where)->with('guild')->limit(($page - 1) * $limit, $limit)->order("create_time", "desc")->select();
        if (count($orders) > 0) {
            $count = GuildWithdrawalsModel::where($where)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $orders, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function withdraw_edit_post()
    {
        $id              = Request::param('id');
        $withdrawalsinfo = GuildWithdrawalsModel::get($id);
        if (!$withdrawalsinfo || $withdrawalsinfo->status == 1) {
            return self::bulidFail("提现申请不存在或已处理");
        }
        $trade_no = Request::param('trade_no');
        if ($withdrawalsinfo->save(['trade_no' => $trade_no, 'status' => 1, 'operate_time' => nowFormat()])) {
            // 记录日志
            $log_content = "通过工会提现，ID：{$withdrawalsinfo->id}，金额{$withdrawalsinfo->cash}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail("处理失败");
    }

    public function withdraw_edit_refuse()
    {
        $id              = Request::param('id');
        $withdrawalsinfo = GuildWithdrawalsModel::get($id);
        if (!$withdrawalsinfo || $withdrawalsinfo->status == 1) {
            return self::bulidFail("提现申请不存在或已处理");
        }
        Db::startTrans();
        if ($withdrawalsinfo->save(['status' => 2, 'operate_time' => nowFormat()])) {
            //归还克拉
            if ($withdrawalsinfo->type == 1) {
                //主播提现，返还克拉至公会账户
                $anchor          = GuildModel::get($withdrawalsinfo->guild_id);
                $anchor->diamond = ['inc', $withdrawalsinfo->diamond];
                if ($anchor->save()) {
                    Db::commit();
                    // 记录日志
                    $log_content = "拒绝工会提现，ID：{$withdrawalsinfo->id}，金额{$withdrawalsinfo->cash}";
                    parent::addAdminLog($log_content);

                    return self::bulidSuccess([]);
                } else {
                    Db::rollback();
                    return self::bulidFail("处理失败");
                }
            }
            return self::bulidSuccess([]);
        }
        return self::bulidFail("处理失败");
    }

    public function edit_abnormal()
    {
        $id              = Request::param('id');
        $withdrawalsinfo = GuildWithdrawalsModel::get($id);
        if (!$withdrawalsinfo || $withdrawalsinfo->status == 1) {
            return self::bulidSuccess([]);
        }
        if ($withdrawalsinfo->save(['status' => 3, 'operate_time' => nowFormat()])) {
            // 记录日志
            $log_content = "设置工会提现为异常单，ID：{$withdrawalsinfo->id}，金额{$withdrawalsinfo->cash}";
            parent::addAdminLog($log_content);
            return self::bulidSuccess([]);
        }
        return self::bulidFail("处理失败");
    }

    /**
     * 入会退会申请
     * @return mixed
     */
    public function apply()
    {
        $type_cate = GuildUserApplyModel::TYPE_CATE;
        $this->assign('type_cate', $type_cate);
        return $this->fetch();
    }


    public function get_apply_list()
    {
        $type      = Request::param("type");
        $status    = Request::param("status");
        $anchor_id = Request::param("anchor_id");
        $guild_id  = Request::param("guild_id");

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [];
        if (is_numeric($type)) {
            $where["type"] = $type;
        }
        if (is_numeric($status)) {
            $where["status"] = $status;
        }
        if (is_numeric($anchor_id)) {
            $where["uid"] = $anchor_id;
        }
        if (is_numeric($guild_id)) {
            $where["guild_id"] = $guild_id;
        }

        $userlist = GuildUserApplyModel::with(['user', 'guild'])
            ->where($where)->limit(($page - 1) * $limit, $limit)
            ->order("id", "desc")->select();

        if (count($userlist) > 0) {
            $count = GuildUserApplyModel::where($where)->count();

            foreach ($userlist as &$item) {
                $item->type_text = $item->type_text;
            }

            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }


    /**
     * 转会申请
     * @return mixed
     */
    public function transfer()
    {
        return $this->fetch();
    }


    public function get_transfer_list()
    {
        $status    = Request::param("status");
        $anchor_id = Request::param("anchor_id");
        $page      = Request::param("page");
        $limit     = Request::param("limit");
        $guild_id  = Request::param("guild_id");

        $where = [];
        if (is_numeric($status)) {
            $where[] = "status={$status}";
        }
        if (is_numeric($anchor_id)) {
            $where[] = "uid={$anchor_id}";
        }
        if (is_numeric($guild_id)) {
            $where[] = "(guild_id = {$guild_id} OR into_guild_id = {$guild_id})";
        }

        $where_str = implode(' AND ', $where);

        $guild_transfer_model = new GuildTransferModel();

        $userlist = $guild_transfer_model->with('user')->where($where_str)->limit(($page - 1) * $limit, $limit)
            ->order("id", "desc")->select();

        if (count($userlist) > 0) {
            $count = $guild_transfer_model->where($where_str)->count();

            foreach ($userlist as &$item) {
                // 当前工会审核状态 第一视角是转出
                $item->guild_audit_str = $guild_transfer_model->auditStatusText($item->guild_audit);
                // 转入工会审核状态
                $item->into_guild_audit_str = $guild_transfer_model->auditStatusText($item->into_guild_audit);
                // 平台审核状态
                $item->platform_audit_str = $guild_transfer_model->auditStatusText($item->platform_audit);
                // 操作步骤
                $step            = $guild_transfer_model->auditStep($item);
                $item->step      = $step;
                $item->step_text = $guild_transfer_model->auditSptpText($step);
            }

            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }


    /**
     * 转会审核操作
     * @return \think\response\Json
     */
    public function operate_transfer_status()
    {
        $status = Request::param('status');
        $id     = Request::param('id');
        if ($id < 1) {
            return self::bulidFail('没有相关转会信息');
        }

        if (!in_array($status, [1, 2])) {
            return self::bulidFail('请正确选择操作');
        }

        // 查询转会信息
        $transfer_info = GuildTransferModel::get($id);
        if (empty($transfer_info)) {
            return self::bulidFail('没有相关转会信息');
        }

        if ($status == 1) {
            $user = UserModel::where(['id' => $transfer_info->uid])->find();
            if ($user->status != 0) {
                return self::bulidFail('该用户账号状态异常');
            }

            if ($user->guild_id != $transfer_info->guild_id) {
                return self::bulidFail('用户已不属于该公会');
            }
        }

        if ($transfer_info->status != 0) {
            return self::bulidFail('当前转会申请已经审核过了');
        }
        // 转出工会审核状态，转入工会审核状态
        if ($transfer_info->guild_audit != 1 || $transfer_info->into_guild_audit != 1) {
            return self::bulidFail('工会还未审核完用户的转会申请');
        }

        $transfer_info->platform_audit      = $status;
        $transfer_info->platform_audit_time = nowFormat();
        $transfer_info->status              = $status;
        $transfer_info->operate_time        = nowFormat();

        $notice_content = '转会申请审核被拒绝';
        if ($status == 1) {
            // 查询工会信息
            $guild_info = GuildModel::with('guild')->where()->find();

            $user->guild_id         = $transfer_info->into_guild_id;
            $user->guild_manager_id = 0;
            $user->guild_join_time  = nowFormat();
            $notice_content         = '转会申请审核通过';
        }

        Db::startTrans();
        try {
            if ($status == 1 && !$user->save()) {
                throw new \Exception('操作失败');
            }

            // 修改审核状态
            if (!$transfer_info->save()) {
                throw new \Exception('操作失败');
            }

            // 添加通知
            $data         = [
                'user_id'     => $transfer_info->uid,
                'title'       => '',
                'content'     => $notice_content,
                'create_time' => nowFormat()
            ];
            $notice_model = new NoticeModel($data);
            if (!$notice_model->save($data)) {
                throw new \Exception('操作失败');
            }

            Db::commit();
            return self::bulidSuccess();
        } catch (\Exception $e) {
            Db::rollback();
        }
        return self::bulidFail();
    }
}
